<!--  -->
<template>
  <div class='file-manage-page' v-loading="loading">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item v-for="item in floderPath">
        <div :class="[{ isActivePath: item.floderKey == activePath }, 'menu-path']" @click="getFloderList(item)">
          {{ item.name }}
        </div>
      </el-breadcrumb-item>
    </el-breadcrumb>
    <div class="operate-list">
      <div class="operation">
        <el-button type="primary" plain @click="openUpload">上传文件</el-button>
      </div>
      <div class="operation">
        <el-button type="primary" plain @click="addFloder">新建文件夹</el-button>
      </div>
      <el-dropdown class="operation" @command="handleFileAuthor">
        <el-button type="primary" plain>
          文件授权<el-icon class="el-icon--right"><arrow-down /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="isRead">仅预览</el-dropdown-item>
            <el-dropdown-item command="isDownload">预览下载</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-tooltip content="返回上一级" placement="top-start" effect="light" v-if="floderPath.length > 1">
        <el-button @click="goBackOneLevel" type="text">
          <el-icon :size="22">
            <iconify icon="mingcute:back-fill"></iconify>
          </el-icon>
        </el-button>
      </el-tooltip>
    </div>
    <el-table :data="list" :header-cell-style="{ background: '#e8e8e8' }" style="width: 100%; margin: 20px 0"
      @selection-change="handleSelectionChange" @row-dblclick="handelDbclick">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="fileName" label="文件名称" min-width="150" :show-overflow-tooltip="true"
        sortable></el-table-column>
      <el-table-column prop="fileType" label="文件类型" min-width="150" :show-overflow-tooltip="true"
        sortable></el-table-column>
      <el-table-column prop="fileSize" label="文件大小" min-width="110" :show-overflow-tooltip="true"
        sortable></el-table-column>
      <el-table-column prop="fileDesc" label="文件描述" min-width="150" :show-overflow-tooltip="true"
        sortable></el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="scope">
          <el-tooltip content="预览" effect="dark" v-if="scope.row.isDownload || !scope.row.isRead">
            <el-button @click="preview(scope.row)" type="text">
              <el-icon :size="20">
                <iconify icon="fontisto:preview"></iconify>
              </el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="下载" effect="dark" v-if="!scope.row.folder&&scope.row.isDownload">
            <el-button @click="download(scope.row)" type="text">
              <el-icon :size="20">
                <iconify icon="material-symbols:download-2-outline"></iconify>
              </el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="删除" effect="dark">
            <el-button @click="remove(scope.row)" type="text">
              <el-icon :size="22">
                <iconify icon="material-symbols-light:delete-outline"></iconify>
              </el-icon>
            </el-button>
          </el-tooltip>

          <el-tooltip content="打开" effect="dark" v-if="scope.row.folder">
            <el-button @click="getFloderList(scope.row)" type="text">
              <el-icon :size="22">
                <iconify icon="mdi:folder-arrow-right"></iconify>
              </el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="取消授权" effect="dark">
            <el-button @click="openCancelFile(scope.row)" type="text">
              <el-icon :size="22">
                <iconify icon="mdi:file-undo-outline"></iconify>
              </el-icon>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <w-dialog :closeFree='true' @ok="submitOk" width="600px" title="上传文件" v-model="diaVisible"
      class="file-manage-file-dialog">
      <el-upload ref='upload' :on-exceed="handleExceed" :limit="1" :http-request="fileUplod" :on-change="beforeUpload"
        :auto-upload='false' :file-list="fileList">
        <el-button size="default" icon="paperclip" round>选择文件</el-button>
      </el-upload>
    </w-dialog>
    <w-dialog :closeFree='true' @ok="addFloderOk" width="600px" title="新建文件夹" v-model="addFloderVisible"
      class="file-manage-add-floder-dialog" v-loading="floderLoading">
      <el-form :model="addFloderFrom" :rules="folderRules" :inline="true" ref="floderForm" class="demo-form-inline"
        label-width="100px">
        <el-form-item label="文件夹名称" prop="folderName">
          <el-input v-model="addFloderFrom.folderName" placeholder="请输入文件夹名称"></el-input>
        </el-form-item>
        <el-form-item label="文件类型" prop="fileTypeKey">
          <el-select v-model="addFloderFrom.fileTypeKey" clearable filterable>
            <el-option v-for="item in fileTypeList" :key="item.fileTypePrimaryKey" :label="item.name"
              :value="item.fileTypePrimaryKey"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </w-dialog>
    <fileAuthor v-model="fileAuthorVisible" v-if="fileAuthorVisible" :authorFileKeyList="authorFileKeyList" :authorType="authorType"/>
    <cancelAuthor v-model="cancelAuthorVisible" v-if="cancelAuthorVisible" :cancelFileKey='cancelFileKey' />
  </div>
</template>

<style lang="less">
.file-manage-file-dialog {

  .el-dialog__header,
  .el-dialog__footer {
    border: none !important;
  }
}
</style>
<style lang="less" scoped>
.file-manage-page {
  .operate-list {
    display: flex;
    gap: 20px;
    margin-top: 20px;
  }

  :deep(.el-breadcrumb) {
    .menu-path {
      cursor: pointer;
      font-size: 16px;

      &.isActivePath {
        color: #36f;
      }
    }
  }

}
</style>
<script>
import {
  ElMessageBox
} from 'element-plus'
import { getFileList, uploadFile, getFileType, postFloder, fileAuthVerify, romoveFile } from '@/api/fileManage.js';
import { genFileId } from 'element-plus'
import fileAuthor from './compenents/fileAuthor.vue';
import cancelAuthor from './compenents/cancelAuthor.vue';
export default {
  components: { fileAuthor, cancelAuthor },
  data() {
    return {
      loading: false,
      fileAuthorVisible: false,
      cancelAuthorVisible: false,
      floderPath: [
        {
          name: '文件管理',
          floderKey: ''
        }
      ],
      activePath: '',
      cancelFileKey: '',
      list: [],
      fileList: [],
      authorFileKeyList: [],
      diaVisible: false,
      authorType: null,
      addFloderVisible: false,
      floderLoading: false,
      fileTypeList: [],
      folderRules: {
        folderName: [
          { required: true, message: "请输入文件夹名称", trigger: "blur" },
        ],
      },
      addFloderFrom: {
        folderName: '',
        fileTypeKey: ''
      }
    };
  },
  methods: {
    handleFileAuthor(command) {
      console.log(command)
      this.authorType = command
      this.openFileAuthor()
    },
    goBackOneLevel() {
      this.floderPath.splice(this.floderPath.length - 1)
      let val = this.floderPath[this.floderPath.length - 1]
      this.activePath = val.floderKey
      this.getFileList(val.floderKey)
    },
    openFileAuthor() {
      console.log(this.authorFileKeyList)
      if (this.authorFileKeyList.length == 0) {
        this.$message.warning('请选择文件')
      } else {
        this.fileAuthorVisible = true
      }
    },
    openCancelFile(val) {
      this.cancelFileKey = val.fileKey
      this.cancelAuthorVisible = true
    },
    handleSelectionChange(val) {
      this.authorFileKeyList = val.map(i => i.fileKey)
    },
    preview (val) {
      const routeData={
        path:'/previewPage',
        query:{
          pdfUrl:val.filePdfUrl
        }
      }
      const resloveData = this.$router.resolve(routeData)
      window.open(resloveData.href,'_blank')
    },
    // 下载文件
    download(val) {
      fileAuthVerify({ fileKey: val.fileKey }).then(res => {
        let blob = res.data
        // 创建隐藏的可下载链接        
        let eleLink = document.createElement('a')
        eleLink.download = val.fileName
        eleLink.style.display = 'none'
        // eleLink.href = url        
        eleLink.href = URL.createObjectURL(blob);
        // 触发点击        
        document.body.appendChild(eleLink)
        eleLink.click()
        // 然后移除        
        document.body.removeChild(eleLink)
      })
    },
    // 获取文件列表
    getFloderList(val) {
      let findIndex = this.floderPath.findIndex(item => item.floderKey == val.floderKey)
      if (~findIndex) {
        this.floderPath.splice(findIndex + 1)
      } else {
        this.floderPath.push({
          name: val.name,
          floderKey: val.floderKey
        })
      }
      this.activePath = val.floderKey
      this.getFileList(val.floderKey)
    },
    // 打开新增文件夹
    addFloder() {
      this.addFloderVisible = true
      getFileType().then(({ data }) => {
        if (data.success) {
          this.fileTypeList = data.rows
        } else {
          this.$message.error(`${data.message}`)
          this.loading = false
        }
      })

    },
    // 打开上传文件
    openUpload() {
      this.diaVisible = true
    },
    // 新增文件夹
    addFloderOk() {
      this.$refs.floderForm.validate((valid) => {
        if (valid) {
          let obj = Object.assign({}, this.addFloderFrom, { parentPrimaryKey: this.activePath })
          postFloder(obj).then(res => {
            if (res.data.success) {
              this.$message.success('新增成功')
              this.addFloderVisible = false
              this.getFileList(this.activePath)
            } else {
              this.$message.error(res.data.message)
            }
          })
        }
      })
    },
    handelDbclick(row, column) {
      console.log(row, column)
      if (row.fileType == '文件夹') {
        this.getFloderList(row)
      }
    },
    // 上传文件
    submitOk() {
      this.$refs.upload.submit()
    },
    // 上传文件覆盖
    handleExceed(files) {
      this.$refs.upload.clearFiles()
      const file = files[0]
      file.uid = genFileId()
      this.$refs.upload.handleStart(file)
    },
    // 上传文件前
    beforeUpload(file) {
      if (file.size / 1024 / 1024 > 50) {
        this.$message.error('上传文件最大不超过50MB')
        this.$refs.upload.clearFiles()
        return false
      }
      return true
    },
    // 上传文件方法
    fileUplod(options) {
      // let data = new Blob([options.file], { type: options.file.type })
      let postData = {
        file: options.file,
        fileTypeKey: '',
        pKey: this.activePath
      }
      uploadFile(postData).then(res => {
        if (res.data.success) {
          this.$message.success('上传成功')
          this.diaVisible = false
          this.getFileList(this.activePath)
        }
      })
    },
    async getFileList(folderKey) {
      let res = await getFileList(folderKey)
      let resp = res.data
      if (resp && resp.success == false) {
        this.$message.error(`${resp.message}`)
        this.loading = false
        return
      }
      resp.rows.forEach(i => {
        i.fileSize = (i.fileSize / 1024).toFixed(0) + 'Kb'
        i.fileType = i.folder ? '文件夹' : i.fileName.substr(i.fileName.lastIndexOf('.') + 1)
        i.floderKey = i.fileKey
        i.name = i.fileName
      })
      this.list = resp.rows;
      this.loading = false
    },
    remove(data) {
      ElMessageBox.confirm('是否删除当前文件', '删除提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确认删除',
        cancelButtonText: '取消'
      }).then(() => {
        romoveFile({ filePrimaryKey: [data.fileKey] }).then(res => {
          if (res.data.success) {
            this.$message.success('删除成功')
            this.getFileList(this.activePath)
          }
        })
      }).catch(action => {
        ElMessage.error('已取消删除');
      })

    }
  },
  created() {
    this.getFileList()
  }
}
</script>